package logic

import (
	"common/globals"
	"common/model"
	"context"
	"errors"
	user "user_srv/proto"
)

func (u *UserServer) UserIntegralChange(ctx context.Context, req *user.UserIntegralChangeRequest) (*user.UserIntegralChangeResponse, error) {
	var users model.User
	err := users.GetUserInfoById(int(req.UserId))
	if err != nil {
		return nil, err
	}
	if users.ID == 0 {
		return nil, errors.New("请重新登录")
	}
	var IntegrationAfterOperation int
	switch req.ControlsType {
	case 1:
		IntegrationAfterOperation = users.Points - int(req.OperationIntegral)
	case 2:
		IntegrationAfterOperation = users.Points + int(req.OperationIntegral)
	default:
		return nil, errors.New("请传入合适的规则")
	}

	tx := globals.Db.Begin()
	integralFlowAdd := model.IntegralFlow{
		UserId:                     int(req.UserId),
		ControlsType:               int(req.ControlsType),
		IntegrationBeforeOperation: users.Points,
		OperationIntegral:          int(req.OperationIntegral),
		IntegrationAfterOperation:  IntegrationAfterOperation,
		OperationalReasons:         req.OperationalReasons,
	}
	err = integralFlowAdd.Create()
	if err != nil {
		tx.Rollback()
		return nil, err
	}
	err = users.UpdateUserPointsById(int(req.UserId), IntegrationAfterOperation)
	if err != nil {
		tx.Rollback()
		return nil, err
	}
	tx.Commit()
	return &user.UserIntegralChangeResponse{}, nil
}
